﻿using FYSJcrm.Core.IRepository.PermManage;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Threading.Tasks;

namespace FYSJcrm.Core.Web.Extensions.FilterExtensions
{
    public class CustomerAuthorizeFilter : IAsyncAuthorizationFilter
    {
        private readonly IManagerRepository _managerRepository;

        public CustomerAuthorizeFilter(IManagerRepository managerRepository)
        {
            _managerRepository = managerRepository;
        }

        public async Task OnAuthorizationAsync(AuthorizationFilterContext context)
        {
            var controllerActionDescriptor = context.ActionDescriptor as ControllerActionDescriptor;
            CheckPermissionAttribute[] permAtts = (CheckPermissionAttribute[])controllerActionDescriptor.MethodInfo
                .GetCustomAttributes(typeof(CheckPermissionAttribute), false);

            //没有标注任何的CheckPermissionAttribute，因此也就不需要检查是否登录
            if (permAtts.Length > 0)
            {
                int? userId = context.HttpContext.Session.GetInt32("LoginUserId");

                if (userId == null)
                {
                    context.Result = new ContentResult
                    {
                        Content = "<script>parent.location.href='/AdminManage/Main/Login'</script>",
                        ContentType = "text/html"
                    };

                    return;
                }

                foreach (var permAtt in permAtts)
                {
                    var hasPerm = await _managerRepository.HasPermissionAsync(userId.Value, permAtt.Permission);

                    if (!hasPerm)
                    {
                        context.Result = new ContentResult { Content = "你没有这个权限！" };
                    }
                }
            }
        }
    }
}
